const express = require("express");

// 处理文件上传
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const upload_config = require("config").get("upload_config");

const router = express.Router();
// // 临时上传目录
const upload = multer({ dest: "upload/avatar/" });

router.post("/", upload.single("file"), (req, res) => {
  const file = req.files.file;
  const name = file.name.split(".")[0];
  const joiner = file.path.indexOf(":\\") !== -1 ? "\\" : "/";
  const pathArr = file.path.split(joiner);
  const pathTemp = pathArr[pathArr.length - 1].replace(
    "upload_",
    `upload_${name}_`
  );
  const targetPath = path.join("upload", "avatar", pathTemp);

  fs.rename(file.path, targetPath, function (err) {
    if (err) {
      return res.status(400).send({ message: "上传文件失败" });
    }
    res.status(200).send({
      message: "上传成功",
      data: {
        url: upload_config.get("baseURL") + "/" + targetPath,
      },
    });
  });
});

module.exports = router;
